package cn.netuo.bumbersoll.helper.screen;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.PowerManager;
import android.view.WindowManager;
import android.widget.Toast;

import cn.netuo.bumbersoll.receiver.ScreenOffAdminReceiver;
import lib.grasp.util.L;

/**
 * 锁屏帮助类
 */
public class ScreenHelper {
    private Activity                mActivity;
    private DevicePolicyManager     mPolicyManager;
    private ComponentName           mAdminReceiver;
    private PowerManager            mPm;
    private PowerManager.WakeLock   mLock;
    private boolean                 mIsScreenOn;


    private static ScreenHelper mInstance;

    public static ScreenHelper getInstance(Activity activity){
        if(mInstance == null) mInstance = new ScreenHelper(activity);
        return mInstance;
    }

    private ScreenHelper(Activity activity) {
        mActivity = activity;
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // 禁用无密码锁屏
        mPm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        if(mPm == null) return;
        mLock = mPm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, ":tag");
        mPolicyManager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
        if(mPolicyManager == null) return;
        mAdminReceiver = new ComponentName(activity, ScreenOffAdminReceiver.class);
    }

    /** 释放亮屏锁 */
    public void unLockScreen() {
        // 释放wakeLock
        if(mLock.isHeld()) mLock.release();     // releasea不能息屏, 只是解除屏幕的强制占用
    }

    /** 强制亮屏(指定描述), 再释放锁 */
    public void screenOn() {
        mLock.acquire(100L);                // acquire(毫秒), 当系统没有休眠的情况下是可以点亮的，一旦系统进入休眠状态，则无法点亮屏幕
        mIsScreenOn = true;
    }

    /** 强制锁屏 */
    public void screenOff(){
        boolean admin = mPolicyManager.isAdminActive(mAdminReceiver);
        if (admin) {
            mIsScreenOn = false;
            mPolicyManager.lockNow();

//            SystemClock.sleep(2000);
//            screenOn();
        } else {
            L.logOnly("没有设备管理权限");
        }
    }

}
